/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package utfpr.cp.control;

import edu.uci.ics.crawler4j.url.WebURL;
import java.util.HashSet;
import java.util.List;
import javax.persistence.EntityManager;
import org.apache.http.Header;
import utfpr.cp.model.EntityManagerHelper;
import utfpr.cp.model.ResourceData;
import utfpr.cp.model.ResourceDataDAO;
import utfpr.cp.model.URLData;
import utfpr.cp.model.URLDataDAO;
import utfpr.cp.model.URLTarget;

/**
 *
 * @author Adriano_2
 */
public class ResourceControl {
    public static boolean existResource(String url) {
        return getResource(url).exist();
    }
    
    public static ResourceData getResource(String url) {
        EntityManager em = EntityManagerHelper.getEntityManager();
        ResourceDataDAO dao = new ResourceDataDAO(em);
        return dao.getByUrl(url);
    }
    
    public static boolean create(URLData ownerURL, String content, List<WebURL> links, Header[] responseHeaders, URLTarget target) {
        EntityManager em = EntityManagerHelper.getEntityManager();
        ResourceData resource;
        if (links != null && !links.isEmpty()) {
            resource = new ResourceData(em.merge(ownerURL), content, URLControl.getOrCreateAll(links));
        }
        else {
            resource = new ResourceData(em.merge(ownerURL), content);
        }
        if (responseHeaders != null) {
            for (Header header : responseHeaders) {
                resource.addHeader(header.getName(), header.getValue());
            }
        }
        if (target != null) {
            resource.setTarget(em.merge(target));
        }
        //TODO na teoria se falhar pode ser devido a objetos nao sincronizados
        return ResourceDataDAO.save(resource, em);
    }
}
